package dawnland02.data.map.io.reader.dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

import dawnland02.data.map.model.Matrix;
import dawnland02.data.map.model.MatrixCell;
import dawnland02.data.map.io.MatrixXMLTag;
import dawnland02.data.map.io.reader.MatrixXMLReader;

/**
 * User: Petru Obreja (obrejap@yahoo.com)
 * Date: Sep 16, 2009
 * Time: 7:50:12 PM
 */
public class MatrixXMLDOMReader implements MatrixXMLReader{
    @Override
    public Matrix readMatrix(String fileName) {
        try {
            File file = new File(fileName);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();
            Element root = doc.getDocumentElement();
            if (!root.getNodeName().equals(MatrixXMLTag.MATRIX.getValue())) {
                return null;
            }
            Integer rows = Integer.valueOf(root.getAttribute(MatrixXMLTag.ROWS_ATTRIBUTE.getValue()));
            Integer columns = Integer.valueOf(root.getAttribute(MatrixXMLTag.COLUMNS_ATTRIBUTE.getValue()));
            Matrix matrix = new Matrix(rows, columns);
            NodeList nodeList = doc.getElementsByTagName(MatrixXMLTag.NODE.getValue());
            for (int s = 0; s < nodeList.getLength(); s++) {
                org.w3c.dom.Node domNode = nodeList.item(s);
                if (domNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                    Element elementNode = (Element) domNode;
                    Integer id = Integer.valueOf(elementNode.getAttribute(MatrixXMLTag.ID_ATTRIBUTE.getValue()));
                    Integer x = Integer.valueOf(elementNode.getAttribute(MatrixXMLTag.X_ATTRIBUTE.getValue()));
                    Integer y = Integer.valueOf(elementNode.getAttribute(MatrixXMLTag.Y_ATTRIBUTE.getValue()));
                    Integer type = Integer.valueOf(elementNode.getAttribute(MatrixXMLTag.TYPE_ATTRIBUTE.getValue()));
                    Integer roadLevel = Integer.valueOf(elementNode.getAttribute(MatrixXMLTag.ROAD_LEVEL_ATTRIBUTE.getValue()));
                    matrix.addNode(id, x, y, type, roadLevel);
                }
            }
            return matrix;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
